/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.fragment;

import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.math.BigDecimal;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.CountTimerButton;
import cn.com.dhc.danlu.widget.CountTimerButton.OnInnerClickListener;
import cn.com.dhc.danlu.widget.SlideButton;
import cn.com.dhc.danlu.widget.SlideButton.OnSlideListener;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.regist.VerificationCodeRequest;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 吴海洋(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-08-13 10:32<br/>
 * <p>
 * <p>
 * 红包支付的短信验证页面
 * </p>
 */
@Deprecated
public class ValidationEnvelopFragment extends DialogFragment implements OnClickListener {
    //    private DanluTaskProxy mDanluTaskProxy;
    private ImageView mIv_close;
    private TextView mTv_beyond_tips;
    private CountTimerButton mBtn_code_btn;
    private TextView mTv_error_code_tips;
    private TextView mTv_actived_phone;
    private EditText mEt_smsCode;
    private Button btn_confirm;
    private SlideButton sb_validation;
    private ICommitListener mListener;

    public static ValidationEnvelopFragment newInstance(String telphone, String amout) {
        ValidationEnvelopFragment fragment = new ValidationEnvelopFragment();
        Bundle bundle = new Bundle();
        bundle.putString("phone", telphone);
        bundle.putString("amount", amout);
        fragment.setArguments(bundle);
        return fragment;
    }

//    public void setDanluTaskProxy(DanluTaskProxy mDanluTaskProxy) {
//        this.mDanluTaskProxy = mDanluTaskProxy;
//    }

    private void refreshUI() {
        String amount = getArguments().getString("amount");
        BigDecimal byd = CommonUtils.fenToYuan(new BigDecimal(amount));
        String tips = String.format(getResources().getString(R.string.big_red_packets_tips), byd.toPlainString());
        dividerShowTextStyle(mTv_beyond_tips, tips, tips.indexOf("过") + 1, tips.indexOf("元") + 1, R.color.color_444444, R.color.color_e93c3c, 15, 18);

        String phone = getArguments().getString("phone");
        String activePhone = String.format(getResources().getString(R.string.active_phone_content), phone);
        dividerShowTextStyle(mTv_actived_phone, activePhone, activePhone.indexOf("：") + 1, activePhone.length(), R.color.color_444444, R.color.color_424242, 15, 18);
    }

    private void setCustomeListener() {
        mBtn_code_btn.setInnerClickListener(new OnInnerClickListener() {
            @Override
            public void onClick(View view) {
                // 请求获取短信验证码
                requestGetSmsCode();

                mTv_error_code_tips.setVisibility(View.GONE);
            }

            @Override
            public void onCountFinish() {

            }
        });
        sb_validation.setSlideListener(new OnSlideListener() {
            @Override
            public void onSlideState(boolean isSlideOver) {
                if (isSlideOver) {
                    enableState(true);
                    CommonUtils.setDisAllowInputPhone(mEt_smsCode, false);
                }
            }
        });

    }

    protected void requestGetSmsCode() {
        String phone = getArguments().getString("phone");
        VerificationCodeRequest request = new VerificationCodeRequest();
        request.setTel(phone);
        request.setToken(agent.getToken());
        agent.getApi()
                .getSmsCodeEnvelop(request)
                .compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>() {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        ToastUtil.getInstance().show("短信验证码发送成功");
                        CommonUtils.setDisAllowInputPhone(mEt_smsCode, true);
                        mEt_smsCode.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
                        mBtn_code_btn.startTimer();
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        if (code.equals("1")) {
                            return "手机号格式错误";
                        } else if (code.equals("2")) {
                            return "发送间隔少于1分钟";
                        } else {
                            return "验证码发送失败";
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        mBtn_code_btn.stopTimer();
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    /**
     * 验证码输入框下方提示错误信息
     *
     * @param tips 提示语
     */
    public void setTip(String tips) {
        mTv_error_code_tips.setVisibility(View.VISIBLE);
        mTv_error_code_tips.setText(tips);
    }

    private void enableState(boolean enabled) {
        mBtn_code_btn.setEnabled(enabled);
        CommonUtils.setDisAllowInputPhone(mEt_smsCode, enabled);
        if (enabled) {
            mEt_smsCode.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
        }
        btn_confirm.setEnabled(enabled);
    }

    public void dividerShowTextStyle(TextView textView, String text, int... args) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        try {
            Spannable textSpan = new SpannableStringBuilder(text);
            // 字体大小
            textSpan.setSpan(new AbsoluteSizeSpan(CommonUtils.sp2px(getActivity(), args[4])), 0, args[0], Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textSpan.setSpan(new AbsoluteSizeSpan(CommonUtils.sp2px(getActivity(), args[5])), args[0], args[1], Spannable.SPAN_INCLUSIVE_INCLUSIVE);
            textSpan.setSpan(new AbsoluteSizeSpan(CommonUtils.sp2px(getActivity(), args[4])), args[1], text.length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

            // 颜色
            ForegroundColorSpan strongColor = new ForegroundColorSpan(getResources().getColor(args[3]));
            ForegroundColorSpan defaultColor = new ForegroundColorSpan(getResources().getColor(args[2]));
            textSpan.setSpan(defaultColor, 0, args[0], Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            textSpan.setSpan(strongColor, args[0], args[1], Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            textSpan.setSpan(defaultColor, args[1], text.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            textView.setText(textSpan);
        } catch (Exception e) {
            textView.setText(text);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_close:
                dismiss();
                break;
            case R.id.btn_confirm:
                mTv_error_code_tips.setVisibility(View.GONE);
                confirmLogic();
                break;
            default:
                break;
        }
    }

    private void confirmLogic() {
        String smsCode = mEt_smsCode.getText().toString().trim();
        if (TextUtils.isEmpty(smsCode)) {
            setTip("请输入手机验证码");
            return;
        }

        if (null != mListener) {
            mListener.commit(smsCode);
        }
    }

    private void initView() {
        mIv_close = (ImageView) getView().findViewById(R.id.iv_close);
        mTv_beyond_tips = (TextView) getView().findViewById(R.id.tv_beyond_tips);
        mBtn_code_btn = (CountTimerButton) getView().findViewById(R.id.btn_code_btn);
        mTv_error_code_tips = (TextView) getView().findViewById(R.id.tv_error_code_tips);
        mTv_actived_phone = (TextView) getView().findViewById(R.id.tv_actived_phone);
        mEt_smsCode = (EditText) getView().findViewById(R.id.et_smscode);
        btn_confirm = (Button) getView().findViewById(R.id.btn_confirm);
        sb_validation = (SlideButton) getView().findViewById(R.id.sb_validation);
        mIv_close.setOnClickListener(this);
        btn_confirm.setOnClickListener(this);
    }

    //    @Override
    //    public void onCreate(Bundle savedInstanceState) {
    //        AbstractApplication.get().inject(this);
    //        super.onCreate(savedInstanceState);
    //    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return super.onCreateDialog(savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            int w = (int) (CommonUtils.getScreenWidth(getActivity()) * 0.85);
            dialog.getWindow().setLayout(w, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        return inflater.inflate(R.layout.dl_fragment_validate_envelop, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // 对话框相关属性
        getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        getDialog().setCanceledOnTouchOutside(false);
        getDialog().setCancelable(false);
        initView();
        // 设置初始状态为不可以点击状态
        enableState(false);
        setCustomeListener();
        refreshUI();
    }

    public void setListener(ICommitListener mListener) {
        this.mListener = mListener;
    }

    public interface ICommitListener {
        void commit(String smsCode);
    }
}